package distriKub;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;

public class ChatComClient { // This class is used for chat communication which is based on UDP
	
	private int chatPort = ComRules.chatPort;
	boolean allOK;

	DatagramSocket clientSocket;

	public boolean sendChatMessage(String messageToSend, InetAddress theAddress, int timeToWait) {
		
		allOK = false;
		
		byte[] sendData = new byte[1024];
		byte[] receiveData = new byte[1024];
		
		sendData = messageToSend.getBytes();
		
		/* DatagramPacket Constructor -> public DatagramPacket(byte[] buf, int length, InetAddress address, int port)
		 * Parameters:
		 * buf - the packet data.
		 * length - the packet length.
	     * address - the destination address.
	     * port - the destination port number.
		 */
		DatagramPacket sendPacket = new DatagramPacket(sendData,sendData.length, theAddress, chatPort);
		DatagramPacket receivePacket = new DatagramPacket(receiveData,receiveData.length);
		
		try{ // Sending the packet to it's destination
		clientSocket.send(sendPacket);
		} catch (IOException IOEX){
			System.out.println("\n===> ChatComClient.java ===> Error in clientSocket.send(sendPacket)\n");
			IOEX.printStackTrace();
			allOK = false;
		}
		
		try{ // Receiving the recepient's response
			clientSocket.setSoTimeout(timeToWait);
			clientSocket.receive(receivePacket);
		} catch (IOException IOEX){
			System.out.println("\n===> ChatComClient.java ===> Error in clientSocket.receive(receivePacket)\n");
			IOEX.printStackTrace();
			allOK = false;
		}
		
		String chatAck = new String(receivePacket.getData()).trim();
		System.out.println("===> ChatComClient.java ===> Received back : " + chatAck);
		
		if (chatAck.equals(""+messageToSend.hashCode()))
			allOK = true;
		
		return allOK;
		
	} // End of sendChatMessage method
	
	public void closeChatClient(){
		clientSocket.close();
	}
	
	public ChatComClient(){ // Constructor
		try{
			clientSocket = new DatagramSocket();
			} catch (SocketException SEX){
				System.out.println("\n===> ChatComClient.java ===> Error Creating new DatagramSocket\n");
				SEX.printStackTrace();
			}
	}
}
